import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {Route} from "vue-router";
import {SettingsModule} from "@/core/store/modules/settings";
import {getDict} from "@/core/api/API";
import router from "@/core/router/router";
import {adminHandler} from "@/core/router/router-defend-admin";
import {weiXinHandler} from "@/core/router/router-defend-weixin";

NProgress.configure({showSpinner: false});

router.beforeEach(async (to: Route, _: Route, next: any) => {
    NProgress.start();
    let toPath = to.path;
    ////console.log(toPath)

    //F5的时候，刷一下字典
    if (SettingsModule.refresh) {
        await getDict(toPath);
    }

    //处理微信路由
    if (toPath.indexOf("/weiXin") != -1) {
        await weiXinHandler(to, _, next);
        return;
    }

    //处理管理系统路由
    await adminHandler(to, _, next);

});

/* 路由异常错误处理，尝试解析一个异步组件时发生错误，重新渲染目标页面 */
router.onError((error) => {
    const pattern = /Loading chunk (\d)+ failed/g;
    const isChunkLoadFailed = error.message.match(pattern);
    if (isChunkLoadFailed) {
        // 用路由的replace方法，并没有相当于F5刷新页面，失败的js文件并没有从新请求，
        // 会导致一直尝试replace页面导致死循环，而用 location.reload 方法
        // 相当于触发F5刷新页面，虽然用户体验上来说会有刷新加载察觉，
        // 但不会导致页面卡死及死循环，从而曲线救国解决该问题
        window.location.reload();
        // const targetPath = $router.history.pending.fullPath;
        // $router.replace(targetPath);
    }
});

/**
 * 路由跳转后--监听
 */
router.afterEach((to: Route) => {
    // if (to.path.indexOf("wx-xin/") != -1) {
    //     document.title = "战“疫”应用超市后台管理系统";
    // } else {
    // document.title = to.meta.title;
    // }
    NProgress.done();
});

export default router
